﻿@using System.Reflection
@using System.Linq.Expressions
@using System.ComponentModel.DataAnnotations
@
@using Whoever.Framework.Base
@using Whoever.Framework.Attributes
@using Whoever.Patterns.Website2.Base
@model Whoever.Patterns.Website2.Base.GridModel
@{
    var grid = new WebGrid(rowsPerPage: Model.RowsPerPage);
    grid.Bind(Model.List, autoSortAndPage: false, rowCount: Model.RowsCount);
}
@if (Model.RowsCount > 0)
{
    var colums = new List<WebGridColumn>();
    foreach (var property in Model.EntityType.GetProperties().Where(p => p.GetCustomAttributes(typeof(NotMappedAttribute), true).Count() == 0 && p.GetCustomAttributes(typeof(GridDisplayable), true).Count() > 0))
    {
        GridDisplayable gridDisplayableAttribute = (GridDisplayable)property.GetCustomAttributes(typeof(GridDisplayable), true).First();
        DisplayAttribute displayAttribute = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayAttribute), true).First();
        if (gridDisplayableAttribute.IsForeign)
        {
            var foreignType = property.PropertyType;
            string[] foreignPropertyNames = gridDisplayableAttribute.ForeignPropertyNames.Split(',');
            foreach (var foreignPropertyName in foreignPropertyNames)
            {
                var foreignProperty = foreignType.GetProperty(foreignPropertyName);
                DisplayAttribute foreignDisplayAttribute = (DisplayAttribute)foreignProperty.GetCustomAttributes(typeof(DisplayAttribute), true).First();
                colums.Add(grid.Column(string.Format("{0}.{1}", foreignType.Name, foreignProperty.Name), string.Format("{0} {1}", displayAttribute.Name, foreignDisplayAttribute.Name)));
            }
        }
        else
        {
            colums.Add(grid.Column(property.Name, displayAttribute.Name));
        }
    }
    colums.Add(grid.Column(format: Item => Html.ActionLink("Editar", "Update", new { Id = Item.Id })));
    colums.Add(grid.Column(format: Item => Html.ActionLink("Eliminar", "Delete", new { Id = Item.Id })));
    
    @Html.Partial("_TotalRecords", Model.List.Count())
    @grid.GetHtml(
            tableStyle: "table table-striped", mode: WebGridPagerModes.All,
            columns: colums)
}